package com.health.tools;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.kobjects.base64.Base64;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;
import org.xmlpull.v1.XmlPullParserException;

import com.google.gson.Gson;
import com.health.db.FDbManager;
import com.health.model.PeopleType;
import com.health.model.WebServiceData;
import com.health.model.WebServiceRootData;
import com.health.tablebean.ARCHIVE_BASEINFO;
import com.health.tablebean.ARCHIVE_ENVIRONMENT;
import com.health.tablebean.ARCHIVE_FAMILYHISTORYINFO;
import com.health.tablebean.ARCHIVE_ILLNESSHISTORYINFO;
import com.health.tablebean.BD_DD_INFO;
import com.health.tablebean.HD_PERSONAL_JKTZ;
import com.health.tablebean.webservice.BaseWebServiceBean;
import com.health.tablebean.webservice.Hypertensio;
import com.health.tablebean.webservice.JiBing;
import com.health.tablebean.webservice.JiaZuShi;
import com.health.tablebean.webservice.ShouShu;
import com.health.tablebean.webservice.ShuXue;
import com.health.tablebean.webservice.WaiShang;
import com.health.tablebean.webservice.YiChuanBing;
import com.health.tablebean.webservice.ZhaiYao;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import static com.health.tools.GlobalConts.URL_UPLOAD_DATA;

//更新本机构及管理人员
//同步本机构用户
public class WebService implements OnWebServiceLinstener {
    // private static final String WSDL_URI =
    // "http://192.168.10.154:8081/ehr/webservice/getInfoByOrgUser";
    private static String WSDL_URI;
    private static String NAMESPACE;
    private static String METHOD_NAME;
    private ARCHIVE_BASEINFO mUserInfo;
    private Gson mGson = new Gson();
    private FDbManager mFdbm;
    private SoapObject mRequest;
    private SoapSerializationEnvelope mEnvelope;
    private OnWebServiceLinstener mLinstener;
    public int mSyncCount = 1;
    public int mDataSize = 0;
    private String orgid = "";
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private SimpleDateFormat sdf_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private Context mContext;
    private HashMap<String, Object> params;
    String SOAPACTION;
    private String responseData = "";
    private String downloadType;
    private String uploadType;

    public void setOnWebServiceLinstener(OnWebServiceLinstener linstener) {
        this.mLinstener = linstener;
    }

    public WebService(Context context) {
        mFdbm = FDbManager.getInstance(context);
        mContext = context;

    }

    /**
     * 同步数据
     *
     * @param orgid
     * @throws Exception
     */
    public void synchrodata(String orgid) throws Exception {
        this.orgid = orgid;
        Log.e("orgid______________", orgid);
        WSDL_URI = GlobalConts.getUrlPost() + "webservice/getInfoByOrgUser";
        NAMESPACE = "http://webservice.zy.com/";
        METHOD_NAME = "getInfoByOrgUser";
        new Thread(synchroNetworkTask).start();
    }


    /**
     * 下载数据
     *
     * @param
     * @throws Exception
     */
    public void downloaddata(String serviceUrl, String methodName, String nameSpace, String soapAction,
                             HashMap<String, Object> params, String module) throws Exception {
        WSDL_URI = serviceUrl;
        NAMESPACE = nameSpace;
        METHOD_NAME = methodName;
        SOAPACTION = soapAction;
        this.params = params;
        this.downloadType = module;
        new Thread(downloadNetworkTask).start();
    }

    // public void uploaddata(List<BaseWebServiceBean> wshdatas, String method,
    // String valueKey) throws Exception {
    // this.wshdatas = wshdatas;
    // // http://192.168.10.146:8081/ehr/
    // WSDL_URI = "http://192.168.10.154:8080/ehr/" + "webservice/" + method;
    // this.valueKey = valueKey;
    // NAMESPACE = "http://webservice.zy.com/";
    // METHOD_NAME = "addHypertension";
    // new Thread(uploadNetworkTask).start();
    // }
    public void uploaddata(String method, HashMap<String, Object> params, String module) throws Exception {

        WSDL_URI = URL_UPLOAD_DATA;
//        WSDL_URI = URL_UPLOAD_DATA+"webservice/" + method;
//        WSDL_URI = GlobalConts.getUrlPost() + "webservice/" + method;
        NAMESPACE = "http://webservice.zy.com/";
        METHOD_NAME = method;
        this.params = params;
        this.uploadType = module;
        new Thread(uploadNetworkTask).start();
    }


    public void uploadFile(String method, String fileURL, String fileName, String modules, String cardNum, String type, String id) {
        try {
            FileInputStream fis = new FileInputStream(fileURL);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int count = 0;
            while ((count = fis.read(buffer)) >= 0) {
                baos.write(buffer, 0, count);
            }
            String uploadBuffer = new String(Base64.encode(baos.toByteArray()));

            String namespace = "http://webservice.zy.com/";
            SoapObject soapObject = new SoapObject(namespace, method);
            soapObject.addProperty("name", fileName);  //参数1   图片名
            soapObject.addProperty("bytes", uploadBuffer);   //参数2  图片字符串
            soapObject.addProperty("fileType", type);
            soapObject.addProperty("cardId", cardNum);
            soapObject.addProperty("type ", "png");
            soapObject.addProperty("id ", id);
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER10);
            Element[] header = new Element[1];
            header[0] = new Element().createElement("", "head");
            Element user = new Element().createElement("", "user");
            user.addChild(Node.TEXT, SPUtil.getRegisterImei(mContext));
//			Element module = new Element().createElement("", "module");
//			module.addChild(Node.TEXT, modules);
            Element token = new Element().createElement("", "token");
            token.addChild(Node.TEXT, SPUtil.getToken(mContext));

            header[0].addChild(Node.ELEMENT, user);
//			header[0].addChild(Node.ELEMENT, module);
            header[0].addChild(Node.ELEMENT, token);
            envelope.headerOut = header;


            envelope.bodyOut = mRequest;
            envelope.dotNet = false;
            envelope.setOutputSoapObject(soapObject);
            HttpTransportSE httpTranstation = new HttpTransportSE(GlobalConts.getUrlPost() + "webservice/" + method);
            httpTranstation.call(namespace, envelope);
            SoapPrimitive response = (SoapPrimitive) envelope.getResponse();// 获得返回对象[]
            if (response != null) {
                String strres = response.toString();
                Log.e("strres", strres);
                complete(strres);// 数据上传完成
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //方法：发送网络请求，获取百度首页的数据。在里面开启线程
    private void sendRequestWithHttpClient() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                //用HttpClient发送请求，分为五步
                //第一步：创建HttpClient对象
                HttpClient httpCient = new DefaultHttpClient();
                //第二步：创建代表请求的对象,参数是访问的服务器地址
                HttpGet httpGet = new HttpGet("http://www.baidu.com");

                try {
                    //第三步：执行请求，获取服务器发还的相应对象
                    HttpResponse httpResponse = httpCient.execute(httpGet);
                    //第四步：检查相应的状态是否正常：检查状态码的值是200表示正常
                    if (httpResponse.getStatusLine().getStatusCode() == 200) {
                        //第五步：从相应对象当中取出数据，放到entity当中
                        HttpEntity entity = httpResponse.getEntity();
                        String response = EntityUtils.toString(entity,"utf-8");//将entity当中的数据转换为字符串

                        //在子线程中将Message对象发出去
                        if (response != null) {
                            String strres = response.toString();
                            complete(strres);
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    onError("Exception" + e.getMessage());
                }

            }
        }).start();

    }



    /**
     * 数据下载
     */
    Runnable downloadNetworkTask = new Runnable() {

        @Override
        public void run() {
            try {
                mRequest = new SoapObject(NAMESPACE, METHOD_NAME);
                mEnvelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER10);
                if (params != null && params.size() > 0) {
                    for (Entry<String, Object> item : params.entrySet()) {
                        mRequest.addProperty(item.getKey(), item.getValue().toString());
                    }
                }
                Element[] header = new Element[1];
                header[0] = new Element().createElement("", "head");
                Element user = new Element().createElement("", "user");
                user.addChild(Node.TEXT, SPUtil.getRegisterImei(mContext));
                Element module = new Element().createElement("", "module");
                module.addChild(Node.TEXT, downloadType);
                Element token = new Element().createElement("", "token");
                token.addChild(Node.TEXT, SPUtil.getToken(mContext));

                header[0].addChild(Node.ELEMENT, user);
                header[0].addChild(Node.ELEMENT, module);
                header[0].addChild(Node.ELEMENT, token);
                mEnvelope.headerOut = header;
                /////

                mEnvelope.bodyOut = mRequest;
                mEnvelope.dotNet = false;
                HttpTransportSE httpTransportSE = new HttpTransportSE(WSDL_URI);
                start("正在下载数据...");
                httpTransportSE.call(null, mEnvelope);
                SoapPrimitive response = (SoapPrimitive) mEnvelope.getResponse();// 获得返回对象
                Log.e("data--result:", "数据：" + response);
                if (response != null) {
                    String strres = response.toString();
                    complete(strres);
                }
            } catch (IOException | XmlPullParserException e) {
                e.printStackTrace();
                onError("IOException | XmlPullParserException" + e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                onError("Exception" + e.getMessage());
            }
        }
    };
    // Handler handler = new Handler() {
    // @Override
    // public void handleMessage(Message msg) {
    // super.handleMessage(msg);
    // Bundle data = msg.getData();
    // String val = data.getString("value");
    // Log.i("mylog", "请求结果为-->" + val);
    // // TODO
    // // UI界面的更新等相关操作
    // }
    // };

    /**
     * 上传高血压网络操作相关的子线程
     */
    Runnable uploadNetworkTask = new Runnable() {

        @Override
        public void run() {
            try {
                if (params != null && params.size() > 0) {
                    mRequest = new SoapObject(NAMESPACE, METHOD_NAME);
                    mEnvelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER10);

                    for (Entry<String, Object> item : params.entrySet()) {
                        mRequest.addProperty(item.getKey(), item.getValue().toString());
                    }

                    Element[] header = new Element[1];
                    header[0] = new Element().createElement("", "head");
                    Element user = new Element().createElement("", "user");
                    user.addChild(Node.TEXT, SPUtil.getRegisterImei(mContext));
                    Element module = new Element().createElement("", "module");
                    module.addChild(Node.TEXT, uploadType);
                    Element token = new Element().createElement("", "token");
                    token.addChild(Node.TEXT, SPUtil.getToken(mContext));

                    header[0].addChild(Node.ELEMENT, user);
                    if (!TextUtils.isEmpty(uploadType)) {

                        header[0].addChild(Node.ELEMENT, module);
                    }
                    header[0].addChild(Node.ELEMENT, token);
                    mEnvelope.headerOut = header;
                    mEnvelope.bodyOut = mRequest;
                    mEnvelope.dotNet = false;
                    HttpTransportSE httpTransportSE = new HttpTransportSE(WSDL_URI,1000*60*5);
                    start("正在上传数据...");
                    httpTransportSE.call(null, mEnvelope);
                    SoapPrimitive response = (SoapPrimitive) mEnvelope.getResponse();// 获得返回对象[]
                    if (response != null) {
                        String strres = response.toString();
                        Log.e("strres", strres);
                        complete(strres);// 数据上传完成
                    }
                }
            } catch (IOException | XmlPullParserException e) {
                e.printStackTrace();
                onError("IOException | XmlPullParserException" + e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                onError("Exception" + e.getMessage());
            }

        }
    };
    /**
     * 数据同步网络操作相关的子线程
     */
    Runnable synchroNetworkTask = new Runnable() {

        @Override
        public void run() {
            try {
                mSyncCount = 1;
                mDataSize = 0;
                int pageSize = 100;// 每页多少数据
                int pageNumber = 1;// 第几页
                for (; ; ) {
                    mRequest = new SoapObject(NAMESPACE, METHOD_NAME);
                    mEnvelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER10);
                    mRequest.addProperty("creater", orgid).addProperty("pageSize", pageSize).addProperty("pageNumber",
                            pageNumber);
                    Log.e("123321", orgid + "-----" + pageSize + "-------" + pageNumber);
                    Element[] header = new Element[1];
                    header[0] = new Element().createElement("", "head");
                    Element user = new Element().createElement("", "user");
                    user.addChild(Node.TEXT, SPUtil.getRegisterImei(mContext));
                    Element token = new Element().createElement("", "token");
                    token.addChild(Node.TEXT, SPUtil.getToken(mContext));
                    header[0].addChild(Node.ELEMENT, user);
                    header[0].addChild(Node.ELEMENT, token);
                    mEnvelope.headerOut = header;

                    mEnvelope.bodyOut = mRequest;
                    mEnvelope.dotNet = false;
                    HttpTransportSE httpTransportSE = new HttpTransportSE(WSDL_URI,1000*60*5);
                    Log.e("WSDL_URI", WSDL_URI);
                    Log.e("NAMESPACE", NAMESPACE);
                    Log.e("METHOD_NAME", METHOD_NAME);

                    start("正在获取数据...");
                    httpTransportSE.call(null, mEnvelope);

                    SoapPrimitive response = (SoapPrimitive) mEnvelope.getResponse();// 获得返回对象
                    Log.e("response", response.toString());
                    if (response != null) {
                        String strres = response.toString();
                        System.out.println("test" + "获取到第" + pageSize + "页数据,共" + pageNumber + "条");
                        onSynchronize("获取到第" + pageNumber + "页数据,共" + pageSize + "条", mSyncCount, mDataSize);
                        if (synchroArchiveBaseInfo(strres) < pageSize) {
                            complete("数据同步完成");
                            return;
                        }
                    }
                    pageNumber += 1;
                }
            } catch (IOException | XmlPullParserException e) {
                e.printStackTrace();
                onError("IOException | XmlPullParserException" + e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                onError("Exception" + e.getMessage());
            }
        }
    };

    /**
     * @param json
     * @return 数据总数
     * @throws Exception
     */
    private int synchroArchiveBaseInfo(String json) throws Exception {
        List<WebServiceData> datas = mGson.fromJson(json, WebServiceRootData.class).getData();
        if (mDataSize == 0) {
            mDataSize = mGson.fromJson(json, WebServiceRootData.class).getTotalSize();
        }
        if (!datas.isEmpty()) {
            for (WebServiceData data : datas) {
                if (data.getCardid().equals("210802199112254336")) {
                    System.out.print("11111");
                }
                System.out.println("正在同步第" + mSyncCount + "条数据" + "共" + mDataSize);
                onSynchronize("正在同步第" + mSyncCount + "条数据", mSyncCount, mDataSize);
                List<ARCHIVE_BASEINFO> locabs = mFdbm.findAllByWhere(ARCHIVE_BASEINFO.class,
                        "idcard = '" + data.getCardid() + "'");
                if (locabs == null || locabs.isEmpty()) {
                    mFdbm.save(buildBaseInfo(data));
                } else {
                    if (!TextUtils.isEmpty(data.getUpdatetime()) && locabs.get(0).getLAST_UPDATE_DATE() != null) {
//                        if (data.getUpdatetime().length()>10){
//                            if (locabs.get(0).getLAST_UPDATE_DATE().before(sdf_time.parse(data.getUpdatetime()))) {
//                                mFdbm.updata(buildBaseInfo(data), "idcard = '" + data.getCardid() + "'");
//                            }
                        if (!compare_date(locabs.get(0).getLAST_UPDATE_DATE(), data.getUpdatetime())) {
                            mFdbm.updata(buildBaseInfo(data), "idcard = '" + data.getCardid() + "'");
                        }

//                        }else {
//                            if (locabs.get(0).getLAST_UPDATE_DATE().before(sdf.parse(data.getUpdatetime()))) {
//                                mFdbm.updata(buildBaseInfo(data), "idcard = '" + data.getCardid() + "'");
//                            }
//                        }
                    } else if (!TextUtils.isEmpty(data.getCreatetime()) && locabs.get(0).getLAST_UPDATE_DATE() != null) {
//                        if (data.getCreatetime().length()>10){
//                            if (locabs.get(0).getLAST_UPDATE_DATE().before(sdf_time.parse(data.getCreatetime()))) {
//                                mFdbm.updata(buildBaseInfo(data), "idcard = '" + data.getCardid() + "'");
//                            }
                        if (!compare_date(locabs.get(0).getLAST_UPDATE_DATE(), data.getCreatetime())) {
                            mFdbm.updata(buildBaseInfo(data), "idcard = '" + data.getCardid() + "'");
                        }
//                        }else{
//                            if (locabs.get(0).getLAST_UPDATE_DATE().before(sdf.parse(data.getCreatetime()))) {
//                                mFdbm.updata(buildBaseInfo(data), "idcard = '" + data.getCardid() + "'");
//                            }
//                        }

                    }
                }
                mSyncCount += 1;
            }
        }
        return datas.size();
    }

    /**
     * 比较两个时间的大小，dt1大于DATE2，返回true，否则返回false
     *
     * @param dt1
     * @param DATE2
     * @return
     */
    public boolean compare_date(Date dt1, String DATE2) {

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            if (DATE2.length() > 10) {
                Date dt2 = df.parse(DATE2);
                if (!(dt1.getTime() < dt2.getTime())) {
                    return true;
                } else {
                    return false;
                }
            } else {
                Date dt2 = sdf.parse(DATE2);
                if (dt1.getTime() > dt2.getTime()) {
                    return true;
                } else {
                    return false;
                }
            }

        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return false;
    }

    private ARCHIVE_BASEINFO buildBaseInfo(WebServiceData data) throws ParseException, Exception {
        if (data == null) {
            throw new Exception("WebService.buildData(Data data) ::data not null");
        }
        // System.out.println(data.getDELFLAG);
        // System.out.println(data.getDelflag());
        ARCHIVE_BASEINFO userInfo = new ARCHIVE_BASEINFO();

        userInfo.setARCHIVEID(data.getArchivesNo());
        userInfo.setSEX(data.getSex());
        userInfo.setADDR(data.getAddress());
        userInfo.setHOUSEHOLD_ADDR(data.getGbname());
        if (!TextUtils.isEmpty(data.getBirthday())) {
            userInfo.setBIRTHDAY(sdf.parse(data.getBirthday()));
        }
        userInfo.setCUSTOMERNAME(data.getName());
        userInfo.setNATION(data.getNation());
        userInfo.setMINORITY(minzuName(data.getNation()));
        userInfo.setPHONE(data.getMobile());
        userInfo.setDOCTOR(data.getDutyDoctor());
        userInfo.setIDCARD(data.getCardid());

        // 行政信息
        userInfo.setPROVINCE(data.getProvince());
        userInfo.setCITY(data.getCity());
        userInfo.setCOUNTY(data.getCounty());
        userInfo.setSTREET(data.getStreet());
        userInfo.setCOMMITTEE(data.getCommittee());
        userInfo.setUPDATEORG(data.getUpdateorg());
        // userInfo.setTOWNNAME(data.gettOWNNAME);
        // userInfo.setVILLAGENAME(data.getIdcardVas());
        // userInfo.setTOWNNAME(sp.getString("str_xz", ""));
        // userInfo.setVILLAGENAME(sp.getString("str_cz", ""));
        userInfo.setTOWNNAME(SPUtil.getstr_xz(mContext));
        userInfo.setVILLAGENAME(SPUtil.getstr_cz(mContext));
        // 创建信息
        userInfo.setCARDTYPE(data.getCardtype());
        userInfo.setCREATER(data.getCreater());
        if (!TextUtils.isEmpty(data.getCreatetime())) {
            if (data.getCreatetime().length() > 10) {
                userInfo.setCREATED_DATE(sdf_time.parse(data.getCreatetime()));
            } else {
                userInfo.setCREATED_DATE(sdf.parse(data.getCreatetime()));
            }
        }
        userInfo.setCREATED_BY(data.getCreater());
        userInfo.setCREATEORG(data.getCreateorg());
        // userInfo.setCREATEUNIT(data.getCreateorg());
        userInfo.setCREATEUNIT_NAME(SPUtil.getstr_jddw(mContext));
        // userInfo.setCREATEMEN_NAME(data.getCreater());
        // userInfo.setCUSTOMERID(data.getid);
        if(TextUtils.isEmpty(data.getModified())){
            userInfo.setMODIFIED(data.getCreater());
        }else{
            userInfo.setMODIFIED(data.getModified());
        }

        String year="";
        if(data.getCardid().length()<11){

        }else{
            year = data.getCardid().substring(6, 10);
        }

        Calendar c = Calendar.getInstance();
        int age=0;
        try {
            age = c.get(Calendar.YEAR) - Integer.parseInt(year);
        }catch (Exception e){
            age=40;
        }

        if (age >= 65) {
            String population = PeopleType.OLD;
            if (!TextUtils.isEmpty(userInfo.getPOPULATION_TYPE())) {
                if (population.equals(PeopleType.YBRQ)) {

                }
                String pop = userInfo.getPOPULATION_TYPE();
                String[] pops = pop.split(",");
                if (!Arrays.asList(pops).contains(population)) {
                    pop = pop + "," + population;
                    userInfo.setPOPULATION_TYPE(pop);
                }
            } else {
                userInfo.setPOPULATION_TYPE(population);
            }
        } else {
            userInfo.setPOPULATION_TYPE(PeopleType.YBRQ);
        }
//        userInfo.setPOPULATION_TYPE(calcPopulation(data));

        if (!TextUtils.isEmpty(data.getUpdatetime())) {
            if (data.getUpdatetime().length() > 10) {
                userInfo.setLAST_UPDATE_DATE(sdf_time.parse(data.getUpdatetime()));
            } else {
                userInfo.setLAST_UPDATE_DATE(sdf.parse(data.getUpdatetime()));
            }
        }

        if(TextUtils.isEmpty(data.getModified())){
            userInfo.setLAST_UPDATE_BY(data.getCreater());
        }else{
            userInfo.setLAST_UPDATE_BY(data.getModified());
        }


        userInfo.setCULTURE(data.getEducation());
        userInfo.setJOB(data.getOccupation());
        userInfo.setMARITALSTATUS(data.getMarriage());
        userInfo.setBLOODTYPE(data.getBloodType());
        userInfo.setLIVETYPE(data.getDomicileType());
        userInfo.setMEDICALPAYTYPE(data.getPaymentMode()); // 医疗支付方式
        userInfo.setMEDICALPAYTYPE_OTHER(data.getRes7());
        userInfo.setPILLALLERGIC(data.getYwgms());// 药物过敏史
        userInfo.setEXPOSURE(data.getYwbls());// 有无暴露史
        userInfo.setWORKUNIT(data.getUnitName());// 工作单位
        userInfo.setCONTACTNAME(data.getLinkmanName());// 联系人姓名
        userInfo.setCONTACTPHONE(data.getLinkmanPhone());// 联系人电话
        userInfo.setRH(data.getRh());
        ZhaiYao zhaiyao = data.getZhaiyao();
        userInfo.setPILLALLERGIC(zhaiyao.getAllergicSource());
        userInfo.setPILLALLERGIC_OTHER(zhaiyao.getAllergicOther());
        userInfo.setEXPOSURE(zhaiyao.getRes9());
        userInfo.setDISEASE(data.getYcbs());// 遗传病史
        userInfo.setDISEASENDITION(zhaiyao.getDisability());
        userInfo.setDISEASENDITION_EX(zhaiyao.getDisabilityOther());
        List<ShouShu> ss = data.getSs();//手术
        List<WaiShang> wais = data.getWais();//外伤
        List<ShuXue> shux = data.getShux();//输血
        List<JiBing> jbs = data.getJb();//疾病
        YiChuanBing yichuanbing = data.getYichuanbing();
        if (yichuanbing != null) {
            userInfo.setDISEASE_EX(yichuanbing.getHeredityhistory());//遗传病
        }

        List<ARCHIVE_ILLNESSHISTORYINFO> oldList = mFdbm.findAllByWhere(ARCHIVE_ILLNESSHISTORYINFO.class, "IDCARD = " + "'" + data.getCardid() + "'");
        if (oldList.size() > 0) {
            for (ARCHIVE_ILLNESSHISTORYINFO illnesshistoryinfo : oldList) {
                mFdbm.delete(illnesshistoryinfo);
            }
        }

        if (jbs != null && jbs.size() > 0) {
            for (JiBing jb : jbs) {
                if (jb != null) {
                    String formerlyType = jb.getFormerlyType();
                    if (!TextUtils.isEmpty(formerlyType)) {
                        String[] split = formerlyType.split(",");
                        for (int i = 0; i < split.length; i++) {
                            ARCHIVE_ILLNESSHISTORYINFO history = new ARCHIVE_ILLNESSHISTORYINFO();
                            if ("DM99-01_2".equals(split[i])) {
                                JBRQData.saveJBLX(PeopleType.GXY, userInfo);
                            } else if ("DM99-01_3".equals(split[i])) {
                                JBRQData.saveJBLX(PeopleType.TNB, userInfo);
                            } else if ("DM99-01_4".equals(split[i])) {
                                JBRQData.saveJBLX(PeopleType.GXB, userInfo);
                            } else if ("DM99-01_7".equals(split[i])) {
                                JBRQData.saveJBLX(PeopleType.NCZ, userInfo);
                            } else if ("DM99-01_8".equals(split[i])) {
                                JBRQData.saveJBLX(PeopleType.JSB, userInfo);
                            } else if ("DM99-01_9".equals(split[i])) {
                                JBRQData.saveJBLX(PeopleType.FJH, userInfo);
                            }

                            history.setILLNESSNAME_OTHER(jb.getDiseaseOther());
                            if (!TextUtils.isEmpty(jb.getAskDate())) {
                                history.setDIAGNOSETIME(GlobalConts.dateFormat.parse(jb.getAskDate()));
                            }
                            history.setILLNESSTYPE("1");
                            history.setILLNESSNAME(split[i]);
                            history.setTHERIOMA(jb.getCancer());
                            history.setJOBILLNESS(jb.getIndustrialDisease());
                            history.setILLNESS_OTHER(jb.getDiseaseOther());
                            history.setIDCARD(data.getCardid());
                            mFdbm.save(history);
                        }
                    }
                }
            }
        }

        if (ss != null && ss.size() > 0) {
            for (ShouShu s : ss) {
                if (s != null) {
                    ARCHIVE_ILLNESSHISTORYINFO history = new ARCHIVE_ILLNESSHISTORYINFO();
                    history.setILLNESSNAME_OTHER(s.getOpsName());
                    if (!TextUtils.isEmpty(s.getOpsDate())) {
                        history.setDIAGNOSETIME(GlobalConts.dateFormat.parse(s.getOpsDate()));
                    }
                    history.setILLNESSTYPE("2");
                    history.setIDCARD(data.getCardid());
                    mFdbm.save(history);
                }

            }
        }


        if (wais != null && wais.size() > 0) {
            for (WaiShang ws : wais) {
                if (ws != null) {
                    ARCHIVE_ILLNESSHISTORYINFO history = new ARCHIVE_ILLNESSHISTORYINFO();
                    history.setILLNESSNAME_OTHER(ws.getCutPart());
                    if (!TextUtils.isEmpty(ws.getCutDate())) {
                        history.setDIAGNOSETIME(GlobalConts.dateFormat.parse(ws.getCutDate()));
                    }
                    history.setILLNESSTYPE("3");
                    history.setIDCARD(data.getCardid());
                    mFdbm.save(history);
                }

            }
        }


        if (shux != null && shux.size() > 0) {
            for (ShuXue sx : shux) {
                if (sx != null) {
                    ARCHIVE_ILLNESSHISTORYINFO history = new ARCHIVE_ILLNESSHISTORYINFO();
                    history.setILLNESSNAME_OTHER(sx.getBloodReason());
                    if (!TextUtils.isEmpty(sx.getBloodDate())) {
                        history.setDIAGNOSETIME(GlobalConts.dateFormat.parse(sx.getBloodDate()));
                    }
                    history.setILLNESSTYPE("4");
                    history.setIDCARD(data.getCardid());
                    mFdbm.save(history);
                }

            }
        }

        List<ARCHIVE_FAMILYHISTORYINFO> historys = mFdbm.findAllByWhere(ARCHIVE_FAMILYHISTORYINFO.class,
                "IDCARD = '" + data.getCardid() + "'");
        if (historys.size() > 0) {
            for (ARCHIVE_FAMILYHISTORYINFO his : historys) {
                mFdbm.delete(his);
            }
        }

        List<JiaZuShi> jiazs = data.getJiazs();
        if (jiazs != null && jiazs.size() > 0) {
            ARCHIVE_FAMILYHISTORYINFO history = new ARCHIVE_FAMILYHISTORYINFO();
            for (int i = 0; i < jiazs.size(); i++) {
                if (jiazs.get(i) != null) {
                    if ("DM01-06_5_51".equals(jiazs.get(i).getRelation())) {
                        history.setFATHERHISTORY(jiazs.get(i).getMedicalhistory());
                        history.setFATHERHISTORY_OTHER(jiazs.get(i).getReg0());
                    } else if ("DM01-06_5_52".equals(jiazs.get(i).getRelation())) {
                        history.setMOTHERHISTORY(jiazs.get(i).getMedicalhistory());
                        history.setMOTHERHISTORY_OTHER(jiazs.get(i).getReg0());
                    } else if ("DM01-06_7".equals(jiazs.get(i).getRelation())) {
                        history.setBROTHERSISTERHISTORY(jiazs.get(i).getMedicalhistory());
                        history.setBROTHERSISTERHISTORY_OTHER(jiazs.get(i).getReg0());
                    } else if ("DM01-06_2".equals(jiazs.get(i).getRelation())) {
                        history.setCHILDRENHISTORY(jiazs.get(i).getMedicalhistory());
                        history.setCHILDRENHISTORY_OTHER(jiazs.get(i).getReg0());
                    }
                    history.setIDCARD(data.getCardid());
                    if (i == jiazs.size() - 1) {
                        mFdbm.save(history);
                    }
                }

            }
        }


        List<ARCHIVE_ENVIRONMENT> aes = mFdbm.findAllByWhere(ARCHIVE_ENVIRONMENT.class,
                "IDCARD = '" + data.getCardid() + "'");
        if (aes.size() > 0) {
            for (ARCHIVE_ENVIRONMENT environment : aes) {
                mFdbm.delete(environment);
            }
        }

        ARCHIVE_ENVIRONMENT environment = new ARCHIVE_ENVIRONMENT();
        environment.setBLOWMEASURE(data.getOutWind());
        environment.setTOILET(data.getHastoilet());
        environment.setDRINKWATER(data.getWater());
        environment.setFUELTYPE(data.getFuel());
        environment.setLIVESTOCKRAIL(data.getFowlType());
        environment.setIDCARD(data.getCardid());
        mFdbm.save(environment);

        userInfo.setIS_UPDATE("N");
        return userInfo;
    }

    /**
     * 民族
     *
     * @param
     * @return
     * @author 王婷婷
     * @date 2017年7月27日 下午2:43:30
     */
    private String minzuName(String nationData) {
        // 1:一般人群，2：儿童，3：孕产妇，4：老年人，5：重精神病，6：高血压，7：糖尿病，8：冠心病，9：脑卒中 10：残疾人
        // 默认值1
        String nationName = "";
        if (!TextUtils.isEmpty(nationData)) {
            List<BD_DD_INFO> minzuInfos = mFdbm.findAllByWhereInInfoDB(BD_DD_INFO.class,
                    "ID = " + "'" + nationData + "'");
            if (minzuInfos.size() > 0) {
                nationName = minzuInfos.get(0).getDATAINFO();
            } else {
                nationName = "";
            }
        }

        return nationName;
    }

    /**
     * 人群分类
     *
     * @param data
     * @return
     * @date 2017年7月27日 下午2:43:15
     */
    private String calcPopulation(WebServiceData data) {
        // 1:一般人群，2：儿童，3：孕产妇，4：老年人，5：重精神病，6：高血压，7：糖尿病，8：冠心病，9：脑卒中 10：残疾人
        // 默认值1
        String population = "";
        if (!TextUtils.isEmpty(data.getIset()) && !("0".equals(data.getIset()))) {
            population += "2,";
        }
        if (!TextUtils.isEmpty(data.getIsfn()) && !("0".equals(data.getIsfn()))) {
            population += "3,";
        }
        if (!TextUtils.isEmpty(data.getIsjsb()) && !("0".equals(data.getIsjsb()))) {
            population += "5,";
        }
        if (!TextUtils.isEmpty(data.getIsgxy()) && !("0".equals(data.getIsgxy()))) {
            population += "6,";
        }
        if (!TextUtils.isEmpty(data.getIstnb()) && !("0".equals(data.getIstnb()))) {
            population += "7,";
        }
        if (!TextUtils.isEmpty(data.getIsgxb()) && !("0".equals(data.getIsgxb()))) {
            population += "8,";
        }
        if (!TextUtils.isEmpty(data.getIsncz()) && !("0".equals(data.getIsncz()))) {
            population += "9,";
        }
        if (!TextUtils.isEmpty(data.getIscjr()) && !("0".equals(data.getIscjr()))) {
            population += "10";
        }
        if ("".equals(population)) {
            population = "1";
        } else {
            if (",".equals(population.substring(population.length() - 1))) {
                population = population.substring(0, population.length() - 1);
            }
        }
        return population;
    }

    @Override
    public void start(String message) {
        if (mLinstener != null) {
            mLinstener.start(message);
        }
    }

    @Override
    public void onSynchronize(String message, int syncCount, int dataSize) {
        if (mLinstener != null) {
            mLinstener.onSynchronize(message, syncCount, mDataSize);
        }
    }

    @Override
    public void complete(String message) {
        if (mLinstener != null) {
            mLinstener.complete(message);
        }
    }

    @Override
    public void onError(String message) {
        if (mLinstener != null) {
            mLinstener.onError(message);
        }
    }

    @Override
    public void onUpload() {
        // TODO Auto-generated method stub

    }
}
